<?php
class WeixinSMS{
	private $appId;
	private $appSecret;

	public function __construct($appId, $appSecret) {
		$this->appId = $appId;
		$this->appSecret = $appSecret;
	}
  
	/*微信发送信息提醒方法start*/
	public function request_post($url = '', $param = '')
	{
		if (empty($url) || empty($param)) {
		return false;
		}
		$postUrl = $url;
		$curlPost = $param;
		$ch = curl_init(); //初始化curl
		curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
		curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
		curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
		$data = curl_exec($ch); //运行curl
		curl_close($ch);
		return $data;
	}

	private function httpGet($url) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_URL, $url);
		$res = curl_exec($curl);
		curl_close($curl);
		return $res;
	}

	public function getToken()
	{
		$data = json_decode(@file_get_contents("http://$_SERVER[HTTP_HOST]/data/access_token_".$this->appId.".js"));
		
		if ($data->expire_time < time()) {
		  $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
		  $res = json_decode($this->httpGet($url));
		  $access_token = $res->access_token;
		  if ($access_token) {
			$data->expire_time = time() + 7000;
			$data->access_token = $access_token;
			$fp = fopen( ROOT."/data/access_token_".$this->appId.".js", "w");
			fwrite($fp, json_encode($data));
			fclose($fp);
		  }
		} else {
		  $access_token = $data->access_token;
		}
		return $access_token;
	}

	public function doSend($touser, $template_id, $url, $data, $topcolor = '#7B68EE')
	{
		$template = array(
			'touser' => $touser,
			'template_id' => $template_id,
			'url' => $url,
			'topcolor' => $topcolor,
			'data' => $data
		);
		$json_template = json_encode($template);
		$accessToken = $this->getToken();
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $accessToken;
		$dataRes = $this->request_post($url, urldecode($json_template));
		if ($dataRes['errcode'] == 0) {
			return true;
		} else {
			return false;
		}
	}
}

